package logic

import (
	"context"
	"fmt"
	"usershop/api/internal/svc"
	"usershop/api/internal/types"
	"usershop/api/pkg"
	"usershop/user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendSmsLogic) SendSms(req *types.SendSmsRequest) (resp *types.ResMsg, err error) {
	// todo: 短信验证码发送

	if !pkg.TelFormat(req.Tel) {
		return &types.ResMsg{
			Cre: -2,
			Msg: "手机格式不正确",
		}, nil
	}

	//先判断短信发送限流
	limit, err := l.svcCtx.UserSrv.SendSmsLimit(l.ctx, &user.SendSmsLimitRequest{Mobile: req.Tel})
	if err != nil {
		return &types.ResMsg{
			Cre: -1,
			Msg: "短信发送失败",
		}, nil
	}

	if limit.Islimit == false {
		return &types.ResMsg{
			Cre: -3,
			Msg: "短信限流10分钟3次",
		}, nil
	}

	code := pkg.Geninitra() //生成短信验证码
	fmt.Println("验证码......:", code)
	pkg.SendSms(req.Tel, code) //调用第三方接口服务发送短信

	//发送短信
	_, err = l.svcCtx.UserSrv.CacheSmsCode(l.ctx, &user.ResSmsCodeRequest{
		Tel:    req.Tel,
		Code:   code,
		Source: req.Source,
	})

	if err != nil {
		return &types.ResMsg{
			Cre: -1,
			Msg: "短信发送失败",
		}, nil
	}

	return &types.ResMsg{
		Cre: 0,
		Msg: "短信发送成功",
	}, nil
}
